<?php
namespace Home\Controller;

use Utuo\ForegroundController;

class GrouponnController extends ForegroundController {
	
	private $groupon = null;
	
	public function _init() {
		exit('sdfsdfsd');
// 		$this->groupon = $this->getCurrentGroupon();
// 		$this->assign("groupon", $this->groupon);
// 		$this->setPageTitle($this->groupon['name']);
	}
	
	public function indexAction() {
		$this->display();
	}
	
	/**
	 * 商品列表
	 */
	public function showAction() {
		$grouponGoodsonList = M("GrouponGoodson a")->join("__GROUPON_GOODS__ b on a.goods_id=b.id")
							 ->where(array(
									'a.status' => array('in', array(1,2)),
									'a.is_deleted' => 0, ))
							 ->field("b.id,b.cid,b.name,b.pic,b.groupon_price,b.price,b.description,b.unit,a.status,a.limit_buy,a.bought_count")->select();
		foreach ( $grouponGoodsonList as &$v ) {
			if ( $v['limit_buy']*1 ) {
				if ($v['limit_buy'] <= $v['bought_count'] ) {
					$v['status'] = 2; // 标记已满员
				}
			}
		}
		$this->assign("grouponList", $grouponGoodsonList);
		$this->display("Activity/Groupon/show");
	}
	
	/**
	 * 订单提交
	 */
	public function applyAction() {
		C("TOKEN_ON", false);
		$product = I( 'product' );
		$d = D('GrouponOrder');
		if ( false === $d->create() ) {
			$this->ajaxError ( $d->getError() );
		}
		$tel = $d->tel;
		$name = $d->name;
		$roomId = $d->room_id;
		if ($this->groupon['status'] == 0 ) {
			$this->ajaxError ( '活动未开始' );
		} elseif ($this->groupon['status'] == 2 ) {
			$this->ajaxError ( '活动已结束' );
		}
		if ( !is_array($product) ) {
			$this->ajaxError ( '请选择商品后提交!' );
		}
		$ids = array_keys( $product );
		$grouponGoodsLists = M('GrouponGoods a')->join('__GROUPON_GOODSON__ b on a.id=b.goods_id')->where(array('a.id' => array('in', $ids), 'a.status' => 1, 'a.is_deleted' => 0, 'a.cid' => $this->cid))->field("a.*,b.limit_buy,b.bought_count")->select();
		$total_fee = 0;
		$orderGoods = array();
		foreach ( $grouponGoodsLists as $v ) {
			$boughtCount = $product[$v['id']]['count'];
			if ( $boughtCount*1<=0 ) {
				$this->ajaxError('商品"'.$v['name'].'"购买数量要大于0。'); // 购买数量
			}
			if( $v['limit_buy']*1 and ($v['bought_count'] + $boughtCount) > $v['limit_buy'] ) {
				$this->ajaxError ( '商品"'.$v['name'].'"购买的数量已超出库存。');
			}
			$total_fee += $boughtCount*$v['groupon_price'];
			$orderGoods[] = array(
				'order_id' => 0,
				'goods_id' => $v['id'],
				'name' => $v['name'],
				'price' => $v['groupon_price'],
				'count' => $boughtCount,
			);
		}
		if ( $orderGoods ) {
			$order = array('groupon_id' => $this->groupon['id'], 'name' => $name, 'tel' => $tel, 'room_id' => $roomId, 'apply_time' => time(), 'total_fee' => $total_fee);
			$orderId = M("GrouponOrder")->add($order);
			if ( $orderId ) {
				foreach ( $orderGoods as &$v) {
					$v['order_id'] = $orderId;
					$data = array('bought_count' => array('exp', "bought_count+".$product[$v['id']]['count']*1),);
					M('GrouponGoodson')->where('groupon_id=%d and goods_id=%d', $this->groupon['id'], $v['id'] )->save($data);
				}
				if (false !== M('GrouponOrderGoods')->addAll( $orderGoods ) ) {
					$this->ajaxSuccess("我们工作人员会尽快与您联系送货。");	
				}
			}
		} else {
			$this->ajaxError('对不起您没有选择任何商品，或选择的商品已下线。');
		}
		$this->ajaxSuccess("购买失败");
	}
	
	/**
	 * 获得一个团购活动
	 * @return number|NULL
	 */
	private function getCurrentGroupon() {
		$now = time();
		$m = M("Groupon");
		$gid = I('gid', 0, "intval");
		$groupon = $m->where(array('cid' => $this->cid, 'status' => 1, 'id' => $gid,))->find(); // 获得指定的一期
		if( !$groupon ) {
			$groupon = $m->where(array('cid' => $this->cid, 'status' => 1, 'begin_time' => array('elt', $now), 'end_time' => array('gt', $now),))->find(); // 获得当前进行的一期
		}
		if ( !$groupon ) {
			$groupon = M("Groupon")->where(array('cid' => $this->cid, 'status' => 1, 'begin_time' => array('gt', $now), ))->order("begin_time asc")->find(); // 获得即将开始的一期
		}
		if ( !$groupon ) {
			$groupon = M("Groupon")->where(array('cid' => $this->cid, 'status' => 1, 'end_time' => array('elt', $now), ))->order("end_time asc")->find(); // 获得最后完毕的一期
		}
		if ( $groupon ) {
			// 设置团购状态
			if ( $groupon['begin_time'] > time() ) {
				$groupon['status'] = 0;  // 0.未开始
			} elseif ( $groupon['end_time'] < time() ) {
				$groupon['status'] = 2;  // 2.已结束
			} else {
				$groupon['status'] = 1;	 // 1.进行中
			}
			return $groupon;
		}
		return null;
	}
	
}
